package com.woniu.carrent.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Component
public class MyInterceptorHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
//        //设置响应乱码
//        res.setContentType("text/html;charset=utf-8");
//        //创建ObjectMapper对象
//        ObjectMapper mapper = new ObjectMapper();
//        //创建ResponseEntity对象，封装响应信息
//        ResultMessage responseEntity = ResultMessage.fail(""); //
//        //前后端分离项目，有些复杂的的请求，会先发送一个预检请求,这个特殊请求直接放行
//        //POST GET PUT DELETE OPTIONS
//        if(req.getMethod().equals("OPTIONS")){
//            return true;
//        }
//        //获取请求uri地址
//        String uri = req.getRequestURI();
//        System.out.println(uri);
//
//        //1.获取请求中token
//        String token = req.getHeader("token"); //需要这只前端 请求拦截器 和响应拦截器
//        System.out.println(token);
//
//        //2.判断请求中token是否为空或者空串
//        if(token == null || token.equals("")){ //当前用户未登录
//            responseEntity.setCode(530);
//            responseEntity.setMessage("用户未登录");
//            //把错误信息响应给前端
//            res.getWriter().write(mapper.writeValueAsString(responseEntity));
//            return false; //拦截当前请求
//        }
//        System.out.println("携带token为 -->" + token);
//        //1.判断当前token是否合法,返回一个枚举对象
//        TokenEnum tokenEnum = JWTUtil.verify(token);
//
//        if(tokenEnum == TokenEnum.TOKENSUCCESS){ //表示token合法
//            //处理
//            return true;//放行
//        }
//        //判断token过期
//        if(tokenEnum == TokenEnum.TOKENEXPIRE){
//            responseEntity.setCode(531);
//            responseEntity.setMessage("token已过期");
//            //把错误信息响应给前端
//            res.getWriter().write(mapper.writeValueAsString(responseEntity));
//            return false; //拦截当次请求
//        }
//        responseEntity.setCode(532);
//        responseEntity.setMessage("非法token");
//        //把错误信息响应给前端
//        res.getWriter().write(mapper.writeValueAsString(responseEntity));
//        return false;//请求拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("-postHandle-");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("-afterCompletion-");
    }
}
